package opt.power.springdemo.config;

import opt.power.springdemo.interceptor.AccessTokenVerifyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * mvc 拦截器
 *
 * @author xuliduo
 * @date 2017/11/16
 * @description class WebMvcConfiguration
 */
@Configuration
public class WebMvcConfiguration {
    /**
     * token 拦截器
     * 只处理"/api/**"
     *
     * @return WebMvcConfigurer
     */
    @Bean
    public WebMvcConfigurer tokenConfigurer() {
        return new WebMvcConfigurer() {
            @org.jetbrains.annotations.NotNull
            @Bean
            AccessTokenVerifyInterceptor accessTokenVerifyInterceptor() {
                return new AccessTokenVerifyInterceptor();
            }

            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                //token的拦截器
                registry.addInterceptor(accessTokenVerifyInterceptor()).addPathPatterns(Constants.API_PATH);
            }
        };
    }

    /**
     * CORS跨域拦截器
     *
     * @return WebMvcConfigurer
     */
    @Bean
    public WebMvcConfigurer corsConfigurer() {

        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping(Constants.API_PATH)
                        .allowedHeaders("*")
                        .allowedMethods("*")
                        .allowedOrigins("*");

            }
        };
    }
}
